<template>
  <div class="question-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h1>题目管理</h1>
        </div>
      </template>

      <!-- 搜索框和新增按钮 -->
      <div class="header-actions">
        <el-button type="primary" @click="openCreateDialog">新增题目</el-button>
        <el-input
          v-model="searchText"
          placeholder="请输入题目名称进行搜索"
          style="width: 300px"
          @input="handleSearch"
          @clear="clearSearch"
        >
          <template #append>
            <el-button @click="clearSearch">清除</el-button>
          </template>
        </el-input>
      </div>

      <!-- 题目列表 -->
      <el-table :data="questions" border stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" />
        <el-table-column prop="questionText" label="题目" />
        <el-table-column prop="points" label="分值" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" :icon="Edit" @click="openEditDialog(row)"></el-button>
            <el-button type="danger" :icon="Delete" @click="deleteQuestion(row.id)"></el-button>
            <el-button type="info" @click="showQuestionContent(row)">查看题目内容</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="totalElements"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />

      <!-- 新增/编辑题目对话框 -->
      <el-dialog v-model="dialogVisible" :title="isEditMode ? '编辑题目' : '新增题目'" width="50%">
        <el-form :model="form" label-width="100px">
          <el-form-item label="题目名称">
            <el-input v-model="form.questionText" />
          </el-form-item>
          <el-form-item label="选项A">
            <el-input v-model="form.optionA" />
          </el-form-item>
          <el-form-item label="选项B">
            <el-input v-model="form.optionB" />
          </el-form-item>
          <el-form-item label="选项C">
            <el-input v-model="form.optionC" />
          </el-form-item>
          <el-form-item label="选项D">
            <el-input v-model="form.optionD" />
          </el-form-item>
          <el-form-item label="正确答案">
            <el-select v-model="form.correctAnswer" placeholder="请选择正确答案">
              <el-option label="A" value="A" />
              <el-option label="B" value="B" />
              <el-option label="C" value="C" />
              <el-option label="D" value="D" />
            </el-select>
          </el-form-item>
          <el-form-item label="分值">
            <el-input-number v-model="form.points" :min="1" />
          </el-form-item>
          <el-form-item label="题目内容">
            <el-input v-model="form.content" type="textarea" :rows="4" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </template>
      </el-dialog>

      <!-- 查看题目内容对话框 -->
      <el-dialog v-model="contentDialogVisible" title="题目内容" width="50%">
        <el-card>
          <p>{{ selectedQuestionContent }}</p>
        </el-card>
        <template #footer>
          <el-button @click="contentDialogVisible = false">关闭</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from '../axios';
import { ElMessage } from 'element-plus';
import { Delete, Edit } from '@element-plus/icons-vue';

// 题目列表
const questions = ref([]);
// 搜索文本
const searchText = ref('');
// 加载状态
const loading = ref(false);
// 对话框是否可见
const dialogVisible = ref(false);
// 是否为编辑模式
const isEditMode = ref(false);
// 分页相关状态
const currentPage = ref(1); // 当前页码（从 1 开始）
const pageSize = ref(5); // 每页大小
const totalElements = ref(0); // 总数据量

// 表单数据
const form = ref({
  id: null,
  questionText: '',
  optionA: '',
  optionB: '',
  optionC: '',
  optionD: '',
  correctAnswer: '',
  points: 1,
  content: '',
});

// 查看题目内容对话框是否可见
const contentDialogVisible = ref(false);
// 当前选中的题目内容
const selectedQuestionContent = ref('');

// 获取所有题目
const fetchQuestions = async () => {
  loading.value = true;
  try {
    const response = await axios.get('/questions', {
      params: { page: currentPage.value, size: pageSize.value },
    });
    questions.value = response.data.content;
    totalElements.value = response.data.totalElements;
  } catch (error) {
    ElMessage.error('获取题目列表失败');
  } finally {
    loading.value = false;
  }
};

// 根据题目名称搜索
const handleSearch = async () => {
  loading.value = true;
  try {
    const response = await axios.get('/questions/search', {
      params: { questionText: searchText.value },
    });
    questions.value = response.data;
  } catch (error) {
    ElMessage.error('搜索题目失败');
  } finally {
    loading.value = false;
  }
};

// 清除搜索
const clearSearch = () => {
  searchText.value = '';
  fetchQuestions();
};

// 打开新增对话框
const openCreateDialog = () => {
  isEditMode.value = false;
  form.value = {
    id: null,
    questionText: '',
    optionA: '',
    optionB: '',
    optionC: '',
    optionD: '',
    correctAnswer: '',
    points: 1,
    content: '',
  };
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (row) => {
  isEditMode.value = true;
  form.value = { ...row };
  dialogVisible.value = true;
};

// 显示题目内容
const showQuestionContent = (row) => {
  selectedQuestionContent.value = row.content; // 设置当前题目的内容
  contentDialogVisible.value = true; // 打开对话框
};

// 提交表单（新增或编辑）
const submitForm = async () => {
  try {
    if (isEditMode.value) {
      // 更新题目
      const response = await axios.put(`/questions/${form.value.id}`, form.value);
      if (response.status === 200) {
        ElMessage.success('题目更新成功');
      }
    } else {
      // 新增题目
      const response = await axios.post('/questions', form.value);
      if (response.status === 201) {
        ElMessage.success('题目新增成功');
      }
    }
    dialogVisible.value = false;
    fetchQuestions(); // 刷新题目列表
  } catch (error) {
    ElMessage.error('保存题目失败');
  }
};

// 删除题目
const deleteQuestion = async (id) => {
  try {
    await axios.delete(`/questions/${id}`);
    ElMessage.success('题目删除成功');
    fetchQuestions(); // 刷新题目列表
  } catch (error) {
    ElMessage.error('题目删除失败');
  }
};

// 处理每页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchQuestions(); // 每页大小变化时，加载第一页数据
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchQuestions(); // 加载对应页的数据
};

// 初始化时加载第一页数据
onMounted(() => {
  fetchQuestions();
});
</script>

<style scoped>
.question-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.card-header {
  text-align: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

::v-deep.el-table th,
::v-deep.el-table td {
  height: 40px;
  line-height: 40px;
  text-align: center;
}
</style>